package com.huilian.iotbox.admin.wap.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.wap.dao.*;
import com.huilian.iotbox.admin.wap.service.*;
import com.huilian.iotbox.data.common.RedisKey;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.*;
import com.huilian.iotbox.data.enums.*;
import com.huilian.iotbox.data.po.*;
import com.huilian.iotbox.data.properties.ConfigProperties;
import com.huilian.iotbox.data.service.SystemConfigService;
import com.huilian.iotbox.data.service.UserAttributeCommonService;
import com.huilian.iotbox.data.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 谢洛涛
 * @date 2021/1/11 17:35
 */
@Slf4j
@Service
public class MerchantStoreServiceImpl implements MerchantStoreService {

    @Autowired
    private UserService userService;
    @Resource
    private CommodityDao commodityDao;
    @Autowired
    private BrandInfoDao brandInfoDao;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private MerchantStoreDao merchantStoreDao;
    @Resource
    private LedgerMerchantDao ledgerMerchantDao;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private CommodityGroupService commodityGroupService;
    @Autowired
    private CustomerServiceInfoDao customerServiceInfoDao;
    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;
    @Autowired
    private CommodityStoreUpDownService commodityStoreUpDownService;
    @Resource
    private ConfigProperties configProperties;
    @Resource
    private CustomerServiceInfoService customerServiceInfoService;
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
    @Autowired
    private LedgerCommodityDao ledgerCommodityDao;
    @Autowired
    private MerchantBannerDao merchantBannerDao;
    @Resource
    private UserAttributeService userAttributeService;
    @Autowired
    private UserAttributeCommonService userAttributeCommonService;

    @Override
    public List<MerchantStore> findAllMerchantStoreByMchId(MerchantStoreDto merchantStoreDto) {
        merchantStoreDto.setUserId(merchantStoreDto.getUserInfo().getId());
        if (!StringUtils.isEmpty(merchantStoreDto.getStoreName())) {
            merchantStoreDto.setStoreName(merchantStoreDto.getStoreName().trim());
            merchantStoreDto.setStoreName(merchantStoreDto.getStoreName().replaceAll(" ", ""));
        }

        List<MerchantStore> merchantStoreList = merchantStoreDao.findAllMerchantStoreByMchId(merchantStoreDto);

        SystemConfig systemConfig = systemConfigService.findOneSystemConfigById(1);
        if (!StringUtils.isEmpty(systemConfig)) {
            // 设置默认 套餐计量单位
            for (MerchantStore merchantStore : merchantStoreList) {
                if (StringUtils.isEmpty(merchantStore.getMeasuringUnit())) {
                    merchantStore.setMeasuringUnit(systemConfig.getDefaultMeasuringUnit());
                }
            }
        }
        return merchantStoreList;
    }

    @Override
    public Integer[] findAllMerchantStoreIdByUserId(UserInfo userInfo) {
        return merchantStoreDao.findAllMerchantStoreIdByUserId(userInfo);
    }

    @Override
    public List<MerchantStoreVo> findMerchantStoreIdByUserId(UserInfo userInfo) {
        return merchantStoreDao.findMerchantStoreIdByUserId(userInfo);
    }

    @Override
    public ServerResponse updateMerchantStore(MerchantStoreDto merchantStoreDto) {
        // 查询用户未配置收款商户的场地
        List<MerchantStore> merchantStoreList = merchantStoreDao.getMerchantStore(merchantStoreDto);
        if (merchantStoreList != null) {
            for (MerchantStore merchantStore : merchantStoreList) {
                MerchantStoreDto store = new MerchantStoreDto();
                store.setUserId(merchantStore.getUserId());
                store.setId(merchantStore.getId());
                store.setMchId(merchantStoreDto.getMchId());
                merchantStoreDao.update(store);
                redisTemplate.delete(String.format(RedisKey.MERCHANT_STORE, merchantStore.getId()));
            }
        } else {
            return ServerResponse.createByErrorMessage("所有场地已绑定成功无需重新绑定");
        }
        return ServerResponse.createBySuccess("绑定成功");
    }

    @Override
    public MerchantStoreVo findMerchantStoreByUserIdByStoreId(MerchantStore merchantStore) {
        MerchantStoreVo merchantStoreVo = merchantStoreDao.findMerchantStoreByUserIdByStoreId(merchantStore);
        if (StringUtils.isEmpty(merchantStoreVo.getServiceMobilePhone())) {
            // 品牌信息
            BrandInfoVo brandInfoVo = brandInfoDao.findByUserId(merchantStore.getUserId());
            if (!StringUtils.isEmpty(brandInfoVo)) {
                merchantStoreVo.setServiceMobilePhone(brandInfoVo.getServiceMobilePhone());
            }
        }
        MerchantBanner merchantBanner = new MerchantBanner();
        merchantBanner.setMerchantStoreId(merchantStore.getId());
        merchantBanner.setStatus(MerchantBannerStatusEnum.UP_FRAME.getCode());
        List<MerchantBanner> allMerchantBannerByCondition = merchantBannerDao.findAllMerchantBannerByCondition(merchantBanner);
        if (!StringUtils.isEmpty(allMerchantBannerByCondition) && allMerchantBannerByCondition.size() > 0) {
            merchantStoreVo.setNavWeChatAppId(allMerchantBannerByCondition.get(0).getNavWeChatAppId());
        }
        return merchantStoreVo;
    }

    /**
     * 场地列表查询
     *
     * @param merchantStoreDto
     * @return
     */
    @Override
    public PageInfo findMerchantStoreList(MerchantStoreDto merchantStoreDto) {
        PageHelper.startPage(merchantStoreDto.getPageNum(), merchantStoreDto.getPageSize());
        List<MerchantStoreVo> merchantStoreList = merchantStoreDao.findMerchantStoreList(merchantStoreDto);
        SystemConfig systemConfig = systemConfigService.findOneSystemConfigById(1);

        if (!StringUtils.isEmpty(systemConfig)) {
            // 设置默认 套餐计量单位
            for (MerchantStoreVo merchantStoreVo : merchantStoreList) {
                if (StringUtils.isEmpty(merchantStoreVo.getMeasuringUnit())) {
                    merchantStoreVo.setMeasuringUnit(systemConfig.getDefaultMeasuringUnit());
                }
            }
        }

        PageInfo pageInfo = new PageInfo(merchantStoreList);
        return pageInfo;
    }

    @Override
    public ServerResponse updateDefaultStatus(MerchantStoreDto merchantStoreDto) {
        MerchantStoreDto merchantStoreDto1 = new MerchantStoreDto();
        merchantStoreDto1.setDefaultStatus(true);
        merchantStoreDto1.setUserId(merchantStoreDto.getUserId());
        merchantStoreDto1.setId(merchantStoreDao.findDefaultStatus(merchantStoreDto1));
        merchantStoreDto1.setDefaultStatus(false);
        merchantStoreDao.update(merchantStoreDto1);

        merchantStoreDto.setDefaultStatus(true);
        merchantStoreDao.update(merchantStoreDto);

        return ServerResponse.createBySuccess();
    }

    /**
     * 新增场地
     *
     * @param merchantStoreDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse save(MerchantStoreDto merchantStoreDto) {
        if (this.findByUserIdAndStoreName(merchantStoreDto) > 0) {
            return ServerResponse.createByError("场地名称已存在,请重新输入");
        }
        MerchantDto merchantDto = new MerchantDto();
        merchantDto.setMerchantId(merchantStoreDto.getMerchantId());
        merchantDto.setUserId(merchantStoreDto.getUserId());
        MerchantVo merchantVo = merchantService.findByUserIdAndMerchantId(merchantDto);
        if (merchantVo != null) {
            merchantStoreDto.setMchId(merchantVo.getId());
        }

        // 是否设为默认场地
        MerchantStoreDto merchantStore = new MerchantStoreDto();
        merchantStore.setUserInfo(merchantStoreDto.getUserInfo());
        List<MerchantStoreVo> merchantStoreList = merchantStoreDao.findMerchantStoreList(merchantStore);
        if (merchantStoreList.size() == 0) {
            // 在此之前没有创建场地，默认第一个场地是默认场地
            merchantStoreDto.setDefaultStatus(true);
        }
        if (merchantStoreDto.getDefaultStatus()) {
            this.updateDefaultStatus(merchantStoreDto);
        }

        // 费率
        int result = 0;
        String message = "";
        if (merchantStoreDto.getId() > 0) {
            String kk = String.format(RedisKey.MERCHANT_STORE, merchantStoreDto.getId());
            log.info("deleteKey：" + kk);
            redisCacheTemplate.delete(kk);
            result = merchantStoreDao.update(merchantStoreDto);
            message = "修改";
        } else {
//            List<DiscountPackage> discountPackages = discountPackageService.findByMerchantStoreIdList(0);
//            merchantStoreDto.setCustom_isShow(false);
//            merchantStoreDto.setDiscountStatus(false);
//            merchantStoreDto.setMaxDiscountRate(new BigDecimal(0.01000));
//            result = merchantStoreDao.addMerchantStore(merchantStoreDto);
//
//            // 品牌信息
//            BrandInfoVo brandInfoVo = brandInfoDao.findByUserId(merchantDto.getUserId());
//            if (brandInfoVo != null) {
//                CustomerServiceInfoDto customerServiceInfoDto = new CustomerServiceInfoDto();
//                customerServiceInfoDto.setMerchantStoreId(merchantStoreDto.getId());
//                customerServiceInfoDto.setServiceName(brandInfoVo.getServiceName());
//                customerServiceInfoDto.setServiceWeChatNumber(brandInfoVo.getServiceWeChatNumber());
//                customerServiceInfoDto.setServiceWeChatQr(brandInfoVo.getServiceWeChatQr());
//                customerServiceInfoDto.setServiceMobilePhone(brandInfoVo.getServiceMobilePhone());
//                customerServiceInfoDto.setServiceFixedTelephone(brandInfoVo.getServiceFixedTelephone());
//                customerServiceInfoDao.insert(customerServiceInfoDto);
//            }
//
//            // 默认套餐
//            message = "添加";
//            for (DiscountPackage discountPackage : discountPackages) {
//                discountPackage.setMerchantStoreId(merchantStoreDto.getId());
//                discountPackage.setHide(true);
//                discountPackageService.insert(discountPackage);
//            }
//
//            if (RoleEnum.SUB_ACCOUNT.getRoleId().equals(merchantStoreDto.getUserInfo().getRoleId())) {
//                UserStore userStore = new UserStore();
//                userStore.setUserId(merchantStoreDto.getSubUserId());
//                userStore.setStoreId(merchantStoreDto.getId());
//                userStore.setStatus(true);
//                userStoreService.insert(userStore);
//                String key = String.format(RedisKey.WAP_USERINFO, merchantStoreDto.getSubUserId());
//                redisCacheTemplate.delete(key);
//            }
        }
        if (result > 0) {
            // 清除缓存
            String key = String.format(RedisKey.WAP_USERINFO, merchantStoreDto.getSubUserId());
            redisCacheTemplate.delete(key);
            return ServerResponse.createBySuccess(message + "成功");
        } else {
            return ServerResponse.createByError(message + "失败");
        }
    }

    @Override
    public Integer findByUserIdAndStoreName(MerchantStoreDto merchantStoreDto) {
        if (merchantStoreDto.getId() > 0) {
            MerchantStoreDto merchantStoreCondition = new MerchantStoreDto();
            merchantStoreCondition.setId(merchantStoreDto.getId());
            MerchantStore merchantStore = merchantStoreDao.findOneMerchantStoreByCondition(merchantStoreCondition);
            merchantStoreDto.setFormerStoreName(merchantStore.getStoreName());
        }
        return merchantStoreDao.findByUserIdAndStoreName(merchantStoreDto);
    }

    @Override
    public MerchantStoreVo findDefaultStore(MerchantStoreDto merchantStoreDto) {
        return merchantStoreDao.findDefaultStore(merchantStoreDto);
    }

    @Override
    public List<MerchantStoreVo> findAllMerchantStoreByMerchantId(String merchantId) {
        return merchantStoreDao.findAllMerchantStoreByMerchantId(merchantId);
    }

    @Override
    public List<MerchantStoreVo> findNoPageList(MerchantStoreDto merchantStoreDto) {
        return merchantStoreDao.findMerchantStoreList(merchantStoreDto);
    }

    @Override
    public Integer updateNmcId(MerchantStoreDto merchantStoreDto) {
        return merchantStoreDao.updateNmcId(merchantStoreDto);
    }

    @Override
    public Integer updateNmtId(MerchantStoreDto merchantStoreDto) {
        return merchantStoreDao.updateNmtId(merchantStoreDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse updateMessage(MerchantStoreDto merchantStoreDto) {
        merchantStoreDto.setNoticeMessageContentId(merchantStoreDto.getNoticeMessageContentId() > 0 ? merchantStoreDto.getNoticeMessageContentId() : null);
        merchantStoreDto.setNoticeMessageTagId(merchantStoreDto.getNoticeMessageTagId() > 0 ? merchantStoreDto.getNoticeMessageTagId() : null);
        for (Integer storeId : merchantStoreDto.getStoreIds()) {
            merchantStoreDto.setId(storeId);
            merchantStoreDao.updateMessage(merchantStoreDto);
        }
        return ServerResponse.createBySuccess();
    }


    @Override
    public List<MerchantStoreVo> findAllMerchantStoreByListId(MerchantStoreDto merchantStoreDto) {
        return merchantStoreDao.findAllMerchantStoreByListId(merchantStoreDto);
    }

    @Override
    public MerchantStore findOneMerchantStoreById(MerchantStoreDto merchantStoreDto) {
        return merchantStoreDao.findOneMerchantStoreById(merchantStoreDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse saveByApplet(MerchantStoreDto merchantStoreDto) {
        if (this.findByUserIdAndStoreName(merchantStoreDto) > 0) {
            return ServerResponse.createByError("场地名称已存在,请重新输入");
        }

        MerchantDto merchantDto = new MerchantDto();
        merchantDto.setMerchantId(merchantStoreDto.getMerchantId());
        merchantDto.setUserId(merchantStoreDto.getUserId());
        final MerchantVo merchantVo = merchantService.findByUserIdAndMerchantId(merchantDto);
        if (!StringUtils.isEmpty(merchantVo)) {
            merchantStoreDto.setMchId(merchantVo.getId());
            merchantStoreDto.setTiktokRate(merchantVo.getFeeValue());
            merchantStoreDto.setMeiTuanRate(merchantVo.getFeeValue());
        }

        // 是否设为默认场地
        MerchantStoreDto merchantStoreCondition = new MerchantStoreDto();
        merchantStoreCondition.setUserInfo(merchantStoreDto.getUserInfo());
        List<MerchantStoreVo> merchantStoreList = merchantStoreDao.findMerchantStoreList(merchantStoreCondition);
        if (merchantStoreList.size() == 0) {
            // 在此之前没有创建场地，默认第一个场地是默认场地
            merchantStoreDto.setDefaultStatus(true);
        }
        if (merchantStoreDto.getDefaultStatus()) {
            this.updateDefaultStatus(merchantStoreDto);
        }

        // 费率
        int result = 0;
        String message = "";
        if (merchantStoreDto.getId() > 0) {

            MerchantStoreDto dto = new MerchantStoreDto();
            dto.setId(merchantStoreDto.getId());
            dto.setUserInfo(merchantStoreDto.getUserInfo());
            MerchantStore merchantStore = merchantStoreDao.findOneMerchantStoreByIdAndPermission(dto);
            if (StringUtils.isEmpty(merchantStore)) {
                return ServerResponse.createByErrorMessage("场地不存在");
            }

            // 自动投币
            if (!StringUtils.isEmpty(merchantStoreDto.getAutomaticCoin())
                    && !StringUtils.isEmpty(merchantStore.getAutomaticCoin())
                    && merchantStoreDto.getAutomaticCoin().compareTo(merchantStore.getAutomaticCoin()) != 0
            ) {
                deviceService.updateDeviceAutomaticCoin(merchantStoreDto.getId(), merchantStoreDto.getAutomaticCoin());
            }

            String kk = String.format(RedisKey.MERCHANT_STORE, merchantStoreDto.getId());
            log.info("deleteKey：" + kk);
            redisCacheTemplate.delete(kk);

            dto = new MerchantStoreDto();
            dto.setId(merchantStoreDto.getId());
            dto.setUserId(merchantStore.getUserId());
            dto.setStoreName(merchantStoreDto.getStoreName());
            dto.setProvince(merchantStoreDto.getProvince());
            dto.setCity(merchantStoreDto.getCity());
            dto.setDistrict(merchantStoreDto.getDistrict());
            dto.setAddress(merchantStoreDto.getAddress());
            dto.setMchId(merchantStoreDto.getMchId());
            dto.setAutomaticRefund(merchantStoreDto.getAutomaticRefund());
            dto.setAutomaticCoin(merchantStoreDto.getAutomaticCoin());
            dto.setDefaultStatus(merchantStoreDto.getDefaultStatus());
            dto.setLatitude(merchantStoreDto.getLatitude());
            dto.setLongitude(merchantStoreDto.getLongitude());
            dto.setFillInMemberInfo(merchantStoreDto.getFillInMemberInfo());
            dto.setSalesmanId(merchantStoreDto.getSalesmanId());
            dto.setTiktokRate(merchantStoreDto.getTiktokRate());
            dto.setMeiTuanRate(merchantStoreDto.getMeiTuanRate());
            result = merchantStoreDao.update(dto);

            //查询客服
            CustomerServiceInfoDto customerServiceInfoDto = new CustomerServiceInfoDto();
            customerServiceInfoDto.setMerchantStoreId(merchantStoreDto.getId());
            customerServiceInfoDto.setServiceMobilePhone(merchantStoreDto.getServiceMobilePhone());
            customerServiceInfoDto.setUserInfo(merchantStoreDto.getUserInfo());
            CustomerServiceInfoVo customerServiceInfoVo = customerServiceInfoService.findByMerchantStoreId(customerServiceInfoDto);
            if (StringUtils.isEmpty(customerServiceInfoVo)) {
                customerServiceInfoDao.insertServiceMobilePhone(customerServiceInfoDto);
            } else {
                customerServiceInfoDao.updateServiceMobilePhone(customerServiceInfoDto);
            }
            //有appID ,修改
            if (!StringUtils.isEmpty(merchantStoreDto.getNavWeChatAppId())) {
                //查询
                MerchantBanner merchantBanner = new MerchantBanner();
                merchantBanner.setMerchantStoreId(merchantStoreDto.getId());
                merchantBanner.setStatus(MerchantBannerStatusEnum.UP_FRAME.getCode());
                List<MerchantBanner> allMerchantBannerByCondition = merchantBannerDao.findAllMerchantBannerByCondition(merchantBanner);
                if (!StringUtils.isEmpty(allMerchantBannerByCondition) && allMerchantBannerByCondition.size() > 0) {
                    allMerchantBannerByCondition.forEach(item -> {
                        merchantBanner.setId(item.getId());
                        merchantBanner.setNavWeChatAppId(merchantStoreDto.getNavWeChatAppId());
                        merchantBannerDao.updateNavWeChatAppId(merchantBanner);
                    });
                }
            }
            message = "修改";
        } else {
            merchantStoreDto.setCustom_isShow(false);
            merchantStoreDto.setDiscountStatus(false);
            merchantStoreDto.setMaxDiscountRate(new BigDecimal(0.01000));
            merchantStoreDto.setAutomaticCoin(false);
            merchantStoreDto.setAutomaticRefund(false);
            result = merchantStoreDao.addMerchantStore(merchantStoreDto);

            //查询游戏币套餐分组id
            CommodityGroupDto commodityGroupDto = new CommodityGroupDto();
            commodityGroupDto.setType(CommodityGroupTypeEnum.GAME_COIN.getCode());
            commodityGroupDto.setUserId(merchantStoreDto.getUserId());
            CommodityGroup commodityGroup = commodityGroupService.getOneCommodityGroupByUserIdAndType(commodityGroupDto);
            if (StringUtils.isEmpty(commodityGroup)) {
                commodityGroup = new CommodityGroup();
                commodityGroup.setUserId(merchantStoreDto.getUserId());
                commodityGroup.setType(CommodityGroupTypeEnum.GAME_COIN.getCode());
                commodityGroup.setName("游戏币套餐");
                commodityGroupService.insert(commodityGroup);
            }

            //创建默认套餐
            int[] price = {1, 5, 10, 20, 50, 100};
            Commodity commodity = new Commodity();
            commodity.setUserId(merchantStoreDto.getUserId());
            commodity.setType(CommodityTypeEnum.REGULAR.getCode());
            commodity.setCommodityGroupId(commodityGroup.getId());
            commodity.setIsDefault(true);
            commodity.setRecommend(true);
            commodity.setHide(true);
            commodity.setClientTerminal(true);
            commodity.setPosTerminal(true);
            commodity.setGiveCoin(0);
            int sort = 1;
            for (int i = 0; i < price.length; i++) {
                commodity.setSort(sort + i);
                commodity.setRetailPrice(new BigDecimal(price[i]));
                commodity.setRechargeCoin(price[i]);
                commodity.setName(price[i] + "枚游戏币");
                commodity.setType(CommodityTypeEnum.REGULAR.getCode());
                commodityService.insert(commodity);
                //添加套餐上架表
                CommodityStoreUpDownDto cupd = new CommodityStoreUpDownDto();
                cupd.setCommodityId(commodity.getId());
                cupd.setMerchantStoreId(merchantStoreDto.getId());
                cupd.setUserId(merchantStoreDto.getUserId());
                cupd.setRetailPrice(new BigDecimal(price[i]));
                cupd.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
                cupd.setClientTerminal(true);
                cupd.setPosTerminal(true);
                commodityStoreUpDownService.insert(cupd);
            }

            // 品牌信息
            BrandInfoVo brandInfoVo = brandInfoDao.findByUserId(merchantDto.getUserId());
            CustomerServiceInfoDto customerServiceInfoDto = new CustomerServiceInfoDto();
            customerServiceInfoDto.setMerchantStoreId(merchantStoreDto.getId());
            customerServiceInfoDto.setServiceMobilePhone(merchantStoreDto.getServiceMobilePhone());
            if (brandInfoVo != null) {
                customerServiceInfoDto.setBrandInfoId(brandInfoVo.getId());
                customerServiceInfoDto.setServiceName(brandInfoVo.getServiceName());
                customerServiceInfoDto.setServiceWeChatNumber(brandInfoVo.getServiceWeChatNumber());
                customerServiceInfoDto.setServiceWeChatQr(brandInfoVo.getServiceWeChatQr());
                customerServiceInfoDto.setServiceFixedTelephone(brandInfoVo.getServiceFixedTelephone());
                customerServiceInfoDao.insert(customerServiceInfoDto);
            } else {
                BrandInfoDto brandInfoDto = new BrandInfoDto();
                brandInfoDto.setUserId(merchantStoreDto.getUserId());
                brandInfoDto.setServiceMobilePhone(merchantStoreDto.getServiceMobilePhone());
                brandInfoDao.insert(brandInfoDto);
                customerServiceInfoDto.setBrandInfoId(brandInfoDto.getId());
                customerServiceInfoDao.insertServiceMobilePhone(customerServiceInfoDto);
            }

            //自动授权子账号
            UserAttributeDto userAttributeDto = new UserAttributeDto();
            userAttributeDto.setUserId(merchantStoreDto.getUserInfo().getId());
            userAttributeDto.setAttributeId(AttributeEnum.NEW_STORES_ARE_AUTOMATICALLY_AUTHORIZED.getCode());
            List<UserAttribute> userAttributeList = userAttributeService.findByUserId(userAttributeDto);

            List<UserAttribute> userAttributesToInsert = new ArrayList<>();
            for (UserAttribute userAttribute : userAttributeList) {
                UserAttribute ua = new UserAttribute();
                ua.setUserId(userAttribute.getUserId());
                ua.setAttributeId(AttributeEnum.SUB_ACCOUNT_ADMIN_STORE.getCode());
                ua.setMerchantStoreId(merchantStoreDto.getId());
                userAttributesToInsert.add(ua);
            }
            // 批量插入授权场地
            if (!userAttributesToInsert.isEmpty()) {
                userAttributeCommonService.batchInsert(userAttributesToInsert);
                String key = String.format(RedisKey.WAP_USERINFO, merchantStoreDto.getSubUserId());
                redisCacheTemplate.delete(key);
            }
            // 默认套餐
            message = "添加";
        }
        if (result > 0) {
            // 清除缓存
            String key = String.format(RedisKey.WAP_USERINFO, merchantStoreDto.getSubUserId());
            redisCacheTemplate.delete(key);
            return ServerResponse.createBySuccess(message + "成功");
        } else {
            return ServerResponse.createByError(message + "失败");
        }
    }

    @Override
    public MerchantStore findOneMerchantStoreByIdAndPermission(MerchantStoreDto merchantStoreDto) {
        return merchantStoreDao.findOneMerchantStoreByIdAndPermission(merchantStoreDto);
    }

    /**
     * 修改计量单位
     *
     * @param merchantStoreDto
     * @return
     */
    @Override
    public ServerResponse updateMeasuringUnit(MerchantStoreDto merchantStoreDto) {
        if (StringUtils.isEmpty(merchantStoreDto.getId())) {
            return ServerResponse.createByErrorMessage("场地ID不能空");
        }

        if (StringUtils.isEmpty(merchantStoreDto.getMeasuringUnit())) {
            return ServerResponse.createByErrorMessage("计量单位不能空");
        }

        merchantStoreDto.setMeasuringUnit(merchantStoreDto.getMeasuringUnit().trim());
        if (merchantStoreDto.getMeasuringUnit().length() < 1 || merchantStoreDto.getMeasuringUnit().length() > 5) {
            return ServerResponse.createByErrorMessage("计量单位长度请设置在1至5位之间，包含1位以及5位");
        }

        MerchantStoreDto merchantStore = new MerchantStoreDto();
        merchantStore.setId(merchantStoreDto.getId());
        merchantStore.setUserInfo(merchantStoreDto.getUserInfo());
        MerchantStore store = merchantStoreDao.findOneMerchantStoreByIdAndPermission(merchantStore);
        if (StringUtils.isEmpty(store)) {
            return ServerResponse.createByErrorMessage("当前账号下不存在该场地");
        }

        MerchantStoreDto updateStore = new MerchantStoreDto();
        updateStore.setId(merchantStoreDto.getId());
        updateStore.setMeasuringUnit(merchantStoreDto.getMeasuringUnit());

        if (merchantStoreDao.updateById(updateStore) > 0) {
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByErrorMessage("修改不成功，请重试");
    }


    /**
     * 修改套餐模式
     *
     * @param merchantStoreDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServerResponse updatePackageModel(MerchantStoreDto merchantStoreDto) {

        if (StringUtils.isEmpty(merchantStoreDto.getId())) {
            return ServerResponse.createByErrorMessage("场地ID不能为空");
        }

        if (StringUtils.isEmpty(merchantStoreDto.getGameCoinModel())) {
            return ServerResponse.createByErrorMessage("游戏模式不能为空");
        }

        if (StringUtils.isEmpty(merchantStoreDto.getRechargeModel())) {
            return ServerResponse.createByErrorMessage("充值模式不能为空");
        }

        if (StringUtils.isEmpty(merchantStoreDto.getOperatePassword())) {
            return ServerResponse.createByErrorMessage("操作密码不能为空");
        }

        if (merchantStoreDto.getGameCoinModel() && merchantStoreDto.getRechargeModel()) {
            return ServerResponse.createByErrorMessage("套餐模式参数有误，请联系平台");
        }

        if (!merchantStoreDto.getGameCoinModel() && !merchantStoreDto.getRechargeModel()) {
            return ServerResponse.createByErrorMessage("套餐模式参数有误，请联系平台");
        }

        final String operatePassword = merchantStoreDto.getOperatePassword().trim().replaceAll(" ", "");
        if (operatePassword.length() < 6 || operatePassword.length() > 18) {
            return ServerResponse.createByErrorMessage("操作密码格式为6到18位");
        }

        MerchantStore merchantStore = merchantStoreDao.findOneMerchantStoreById(merchantStoreDto);
        if (StringUtils.isEmpty(merchantStore)) {
            return ServerResponse.createByErrorMessage("当前账号不存在该场地");
        }

        UserVo userVo = userService.findOperatePasswordByUserId(merchantStoreDto.getUserInfo().getId());
        boolean matches = passwordEncoder.matches(merchantStoreDto.getOperatePassword(), userVo.getOperatePassword());
        if (!matches) {
            return ServerResponse.createByErrorMessage("操作密码不正确");
        }

        MerchantStoreDto updateStore = new MerchantStoreDto();
        updateStore.setId(merchantStoreDto.getId());
        if (merchantStoreDto.getGameCoinModel()) {
            updateStore.setMeasuringUnit("币");
            updateStore.setPackageModel(MerchantStorePackageModelEnum.GAME_COIN.getCode());
        } else if (merchantStoreDto.getRechargeModel()) {
            updateStore.setMeasuringUnit("元");
            updateStore.setPackageModel(MerchantStorePackageModelEnum.RECHARGE.getCode());
        } else {
            return ServerResponse.createByErrorMessage("套餐模式参数有误，请联系平台");
        }
        merchantStoreDao.updateById(updateStore);

        return ServerResponse.createBySuccess();
    }

    /**
     * 查询场地分账比例
     */
    @Override
    public PageInfo findAreaLedgerProportionAndPage(MerchantStoreDto merchantStoreDto) {
        PageHelper.startPage(merchantStoreDto.getPageNum(), merchantStoreDto.getPageSize());
        List<MerchantStoreVo> merchantStoreList = merchantStoreDao.findAreaLedgerProportionAndPage(merchantStoreDto);
        LedgerMerchantDto ledgerMerchantDto = new LedgerMerchantDto();
        ledgerMerchantDto.setUserId(merchantStoreDto.getUserId());
        for (MerchantStoreVo merchantStoreVo : merchantStoreList) {
            ledgerMerchantDto.setMerchantStoreId(merchantStoreVo.getMerchantStoreId());
            List<LedgerMerchantVo> ledgerMerchantVos = ledgerMerchantDao.findAreaSubLedgerMerchant(ledgerMerchantDto);
            merchantStoreVo.setLedgerMerchantVoList(ledgerMerchantVos);
            merchantStoreVo.setMerchantCount(ledgerMerchantVos.size());
            if (!StringUtils.isEmpty(ledgerMerchantVos) && ledgerMerchantVos.size() > 0) {
                Integer[] ledgerCommodityByLedgerMerchantIdList = ledgerCommodityDao.findLedgerCommodityByLedgerMerchantIdList(ledgerMerchantVos.get(0).getId());
                merchantStoreVo.setCommodityCount(ledgerCommodityByLedgerMerchantIdList.length);
            }

        }
        PageInfo pageInfo = new PageInfo(merchantStoreList);
        return pageInfo;
    }

    @Override
    public ServerResponse updateAsDelById(MerchantStoreDto merchantStoreDto) {
        if (StringUtils.isEmpty(merchantStoreDto.getId())) {
            return ServerResponse.createByErrorMessage("缺少参数：id");
        }

        MerchantStore merchantStore = merchantStoreDao.findOneMerchantStoreById(merchantStoreDto);
        if (StringUtils.isEmpty(merchantStore)) {
            return ServerResponse.createByErrorMessage("该场地未授权此账号");
        }
        DeviceDto deviceDto = new DeviceDto();
        deviceDto.setMerchantStoreId(merchantStoreDto.getId());
        deviceDto.setUserInfo(merchantStoreDto.getUserInfo());
        Integer countDevice = deviceService.findDeviceCountByMerchantStoreId(deviceDto);
        if (countDevice > 0) {
            return ServerResponse.createByErrorMessage("删除出现异常，只允许删除没有设备的场地");
        }

        int result = merchantStoreDao.updateIsDeleteById(merchantStoreDto.getId());

        if (result < 0) {
            return ServerResponse.createByErrorMessage("没有该主键数据:" + merchantStoreDto.getId());
        }

        //删除子账号授权门店
        UserAttributeDto userAttributeDto = new UserAttributeDto();
        userAttributeDto.setMerchantStoreId(merchantStoreDto.getId());
        List<UserAttribute> userAttributeList = userAttributeService.findByMerchantStoreId(userAttributeDto);
        List<UserAttribute> userAttributesToDel = new ArrayList<>(userAttributeList);
        if (userAttributesToDel.size() > 0) {
            userAttributeCommonService.batchDelete(userAttributesToDel);
        }

        return ServerResponse.createBySuccess();
    }

    @Override
    public List<MerchantStoreVo> findMerchantStoreIdByUserIdAndDeviceTypeId(MerchantStoreDto merchantStoreDto) {
        return merchantStoreDao.findMerchantStoreIdByUserIdAndDeviceTypeId(merchantStoreDto);
    }

    /**
     * 查出当前账号有权限的场地，如有上报commodityId就同时查出对应的上架信息
     *
     * @param merchantStoreDto
     * @return
     */
    @Override
    public ServerResponse findStoreShelves(MerchantStoreDto merchantStoreDto) {

        List<MerchantStore> merchantStoreList = merchantStoreDao.findAllMerchantStoreByIdAndPermission(merchantStoreDto);

        if (merchantStoreList.size() == 0) {
            return ServerResponse.createBySuccess(new ArrayList<>());
        }

        List<CommodityStoreUpDownVo> commodityStoreUpDownVoList = new ArrayList<>();
        Map<Integer, CommodityStoreUpDownVo> commodityStoreUpDownVoMap = new HashMap<>();
        if (!StringUtils.isEmpty(merchantStoreDto.getCommodityId())) {
            CommodityStoreUpDownDto commodityStoreUpDownDto = new CommodityStoreUpDownDto();
            commodityStoreUpDownDto.setCommodityId(merchantStoreDto.getCommodityId());
            commodityStoreUpDownDto.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
            commodityStoreUpDownDto.setUserInfo(merchantStoreDto.getUserInfo());
            commodityStoreUpDownVoList = commodityStoreUpDownService.finAllCommodityStoreUpDownByPermission(commodityStoreUpDownDto);
            commodityStoreUpDownVoMap = commodityStoreUpDownVoList.stream().collect(Collectors.toMap(CommodityStoreUpDownVo::getMerchantStoreId, a -> a, (k1, k2) -> k1));
        }

        List<CommodityStoreUpDownVo> commodityStoreUpDownVos = new ArrayList<>();
        for (MerchantStore merchantStore : merchantStoreList) {

            CommodityStoreUpDownVo commodityStoreUpDownVo = commodityStoreUpDownVoMap.get(merchantStore.getId());
            if (StringUtils.isEmpty(commodityStoreUpDownVo)) {
                commodityStoreUpDownVo = new CommodityStoreUpDownVo();
                commodityStoreUpDownVo.setMerchantStoreId(merchantStore.getId());
                commodityStoreUpDownVo.setStoreName(merchantStore.getStoreName());
                commodityStoreUpDownVos.add(commodityStoreUpDownVo);
                continue;
            }

            commodityStoreUpDownVo.setMerchantStoreId(merchantStore.getId());
            commodityStoreUpDownVo.setStoreName(merchantStore.getStoreName());
            commodityStoreUpDownVos.add(commodityStoreUpDownVo);
        }

        return ServerResponse.createBySuccess(commodityStoreUpDownVos);
    }

    @Override
    public ServerResponse receiptQrCode(MerchantStoreDto merchantStoreDto) {
        if (StringUtils.isEmpty(merchantStoreDto.getId())) {
            return ServerResponse.createByErrorMessage("缺少参数:场地id!");
        }
        final MerchantStore merchantStore = merchantStoreDao.findOneMerchantStoreById(merchantStoreDto);
        if (StringUtils.isEmpty(merchantStore)) {
            return ServerResponse.createByErrorMessage("场地不存在或对该场地无权限!");
        }

        StringBuffer qrLink = new StringBuffer(configProperties.getClientBackEndUrl());
        qrLink.append("/client/applet/");
        if (!StringUtils.isEmpty(merchantStore.getDedicatedWeChatApplet())) {
            // 专属微信小程序
            log.info("专属微信小程序-处理");
            qrLink.append(merchantStore.getId());
            qrLink.append("/");
        } else if (!StringUtils.isEmpty(merchantStore.getDedicatedALiApplet())) {
            // 专属支付宝小程序
            log.info("专属支付宝小程序-处理");
            qrLink.append(merchantStore.getId());
            qrLink.append("/");
        } else if (!StringUtils.isEmpty(merchantStore.getDedicatedOfficialAccount())) {
            // 专属微信公众号
            log.info("专属微信公众号-处理");
            qrLink.append(merchantStore.getId());
            qrLink.append("/");
        } else {
            log.info("默认处理");
        }
        qrLink.append("device/offlineCollectionCode?merchantStoreId=");
        qrLink.append(merchantStore.getId());

        log.info("qrLink:{}", qrLink);
        return ServerResponse.createBySuccess(qrLink);
    }

    @Override
    public List<MerchantStore> findAllInventoryByOutTradeNo(MerchantStoreDto merchantStoreDto) {
        if (StringUtils.isEmpty(merchantStoreDto.getOutTradeNo())) {
            throw new RuntimeException("缺少参数:outTradeNo订单号");
        }
        return merchantStoreDao.findAllInventoryByOutTradeNo(merchantStoreDto);
    }

    /**
     * 查询场地门闸设备
     */
    @Override
    public ServerResponse findStoreGateGateDeviceNo(MerchantStoreDto merchantStoreDto) {
        List<MerchantStoreVo> merchantStoreIdByUserIdList = merchantStoreDao.findMerchantStoreIdByUserId(merchantStoreDto.getUserInfo());
        if (StringUtils.isEmpty(merchantStoreIdByUserIdList)) {
            return ServerResponse.createBySuccess(new ArrayList<>());
        }
        List<MerchantStoreVo> list = new ArrayList<>();
        for (MerchantStoreVo merchantStoreVo : merchantStoreIdByUserIdList) {
            merchantStoreVo.setDeviceTypeId(DeviceTypeEnum.GATE_GATE.getCode());
            merchantStoreVo.setDeviceNo(merchantStoreDto.getDeviceNo());
            List<DeviceVo> deviceVoList = deviceService.findGateGateDevice(merchantStoreVo);
            //过滤掉 场地没有绑定门闸设备选项
            if (deviceVoList.size() > 0) {
                deviceVoList.forEach(item -> {
                    StringBuilder sb = new StringBuilder();
                    // 拼接字符串
                    sb.append("门闸");
                    sb.append(item.getDeviceNo());
                    sb.append(StringUtils.isEmpty(item.getAlias()) ? "" : "（" + item.getAlias() + "）");
                    sb.append(StringUtils.isEmpty(item.getName()) ? "" : ",正在【" + item.getName() + "】项目正在使用");
                    item.setGateGateDeviceName(sb.toString());
                });
                merchantStoreVo.setGateGateDeviceList(deviceVoList);
                list.add(merchantStoreVo);
            }
        }
        return ServerResponse.createBySuccess(list);
    }
}
